<template>
  <div v-loading="loading" class="authority-container">
    <div class="top-nav">
      <px-button type="primary" :icon="ArrowLeft" @click="goBack">返回</px-button>
      <div class="nav-location">
        <span class="current-folder">当前文件夹：</span>
        <!-- <span v-if="folderPath.length < 2" class="current-folder">全部文件夹</span> -->
        <px-breadcrumb>
          <px-breadcrumb-item v-for="item in currentPath" :key="item.id">{{ item.name }}</px-breadcrumb-item>
        </px-breadcrumb>
      </div>
      <template v-if="authorityFlag && switchDisabled">
        <px-tooltip content="当前不可关闭权限控制，请前往上一级文件夹关闭">
          <px-switch v-model="authorityFlag" :disabled="switchDisabled" @change="changeAuth" />
        </px-tooltip>
      </template>
      <px-switch v-else v-model="authorityFlag" @change="changeAuth" />
      <span :class="['flag-status', { 'active-status': authorityFlag }]">
        {{ authorityFlag ? "权限设置已开启" : "权限设置未开启" }}
      </span>
    </div>
    <div class="handle-btn">
      <px-button type="primary" :disabled="!authorityFlag" @click="addPerson">添加角色</px-button>
      <px-button :disabled="!authorityFlag" @click="deletePerson">删除</px-button>
    </div>
    <div v-if="authorityFlag" class="table-content">
      <px-table height="calc(100vh - 330px)" :data="tableData" size="small" border class="common-table" @selection-change="tableSelect">
        <px-table-column type="selection" fixed width="55" prop="selection" :selectable="selecTable" align="center" />
        <px-table-column prop="name" :label="columnLabel" min-width="120" show-overflow-tooltip />
        <px-table-column prop="preview" label="预览" width="120">
          <template #default="scope">
            <px-checkbox
              :key="scope.row.rowId + 'preview'"
              v-model="scope.row.preview"
              :disabled="!scope.row.isEdit || !authorityFlag"
              size="large"
            />
          </template>
        </px-table-column>
        <px-table-column prop="download" label="下载" width="120">
          <template #default="scope">
            <px-checkbox
              :key="scope.row.rowId + 'download'"
              v-model="scope.row.download"
              :disabled="!scope.row.isEdit || !authorityFlag"
              size="large"
              @change="val => changeLimit(val, scope.row)"
            />
          </template>
        </px-table-column>
        <px-table-column prop="edit" label="操作" width="120">
          <template #header>
            <span>操作</span>
            <px-tooltip content="新建文件夹、上传文件、对文件、文件夹的重命名、移动、删除操作">
              <px-icon size="16" color="#faad14">
                <Warning />
              </px-icon>
            </px-tooltip>
          </template>
          <template #default="scope">
            <px-checkbox
              :key="scope.row.rowId + 'edit'"
              v-model="scope.row.edit"
              :disabled="!scope.row.isEdit || !authorityFlag"
              size="large"
              @change="val => changeLimit(val, scope.row)"
            />
          </template>
        </px-table-column>
        <px-table-column prop="manage" label="管理" width="120">
          <template #header>
            <span>管理</span>
            <px-tooltip content="对文件、文件夹归档和文件夹权限设置">
              <px-icon size="16" color="#faad14">
                <Warning />
              </px-icon>
            </px-tooltip>
          </template>
          <template #default="scope">
            <px-checkbox
              :key="scope.row.rowId + 'manage'"
              v-model="scope.row.manage"
              :disabled="!scope.row.isEdit || !authorityFlag"
              size="large"
              @change="val => changeLimit(val, scope.row)"
            />
          </template>
        </px-table-column>
        <px-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <div v-if="!scope.row.isEdit">
              <px-tooltip content="编辑" placement="top">
                <px-button
                  link
                  icon="EditPen"
                  type="primary"
                  :disabled="scope.row?.readOnly || !authorityFlag"
                  @click="handleEdit(scope.row, scope.$index)"
                />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button
                  link
                  icon="Delete"
                  type="danger"
                  :disabled="scope.row?.readOnly || !authorityFlag"
                  @click="handleDelete(scope.row, scope.$index)"
                />
              </px-tooltip>
            </div>
            <div v-else>
              <px-tooltip content="保存" placement="top">
                <px-button
                  link
                  icon="Save"
                  type="primary"
                  :disabled="scope.row?.readOnly || !authorityFlag"
                  @click="handleSave(scope.row, scope.$index)"
                />
              </px-tooltip>
              <px-tooltip content="取消" placement="top">
                <px-button
                  link
                  icon="CloseRectangle"
                  type="danger"
                  :disabled="scope.row?.readOnly || !authorityFlag"
                  @click="handleCancel(scope.row, scope.$index)"
                />
              </px-tooltip>
            </div>
          </template>
        </px-table-column>
      </px-table>
    </div>
    <px-dialog v-model="addDialogVisible" title="添加" :before-close="cancelAdd">
      <div v-loading="selectLoading" class="add-container">
        <div v-if="activeName === 'organization'">
          <px-tree-select
            v-model="selectedOption"
            :data="optionList"
            multiple
            :render-after-expand="false"
            show-checkbox
            check-strictly
            check-on-click-node
            filterable
            clearable
            collapse-tags
            :max-collapse-tags="3"
            style="width: 500px"
          />
        </div>
        <div v-else>
          <px-select
            v-model="selectedOption"
            multiple
            placeholder="Select"
            filterable
            all-option
            clearable
            collapse-tags
            :max-collapse-tags="3"
            style="width: 500px"
          >
            <px-option v-for="item in optionList" :key="item.value" :label="item.label" :value="item" />
          </px-select>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="cancelAdd">取消</px-button>
          <px-button type="primary" @click="confirmAdd">确定</px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from "vue";
import { ArrowLeft } from "@px-ui/icons-vue";
import { PxMessage, PxMessageBox } from "px-ui";
import {
  getPersonListAPI,
  getRoleListAPI,
  getWorkListAPI,
  getOrganizationListAPI,
  getAuthorityAPI,
  openAuthorityAPI,
  closeAuthorityAPI,
  saveAuthorityAPI,
  deleteAuthorityAPI
} from "@/api/knowledge/documentManage";

const props = defineProps({
  rowData: {
    type: Object,
    default: () => {}
  },
  folderPath: {
    type: Array,
    default: () => []
  },
  currentNode: {
    type: Object,
    default: () => {}
  }
});
const emits = defineEmits(["goBack"]);

const tabList = ref([
  { name: "person", label: "人员" },
  { name: "role", label: "角色" },
  { name: "work", label: "岗位" },
  { name: "organization", label: "组织" }
]);
const activeName = ref("role");

const state = reactive({
  loading: false,
  authorityFlag: false,
  currentPath: [],
  tableData: [],
  tableSelectedData: [],
  addDialogVisible: false,
  selectLoading: false,
  optionList: [],
  selectedOption: [],
  columnLabel: "角色",
  switchDisabled: false
});
const { loading, authorityFlag, currentPath, tableData, addDialogVisible, selectLoading, optionList, selectedOption, columnLabel, switchDisabled } =
  toRefs(state);

// 返回
const goBack = () => {
  emits("goBack");
};

onMounted(() => {
  if (props.folderPath.length === 0) {
    let arr = [{ id: "F0", name: "全部文件夹" }];
    arr.push({ ...props.rowData });
    state.currentPath = arr;
  } else {
    state.currentPath = props.folderPath;
    state.currentPath.push({ ...props.rowData });
  }
  init();
  getSwitchDisabledStatus();
});

// 权限开关
const changeAuth = async val => {
  const id = props.rowData.id;
  if (val) {
    await openAuthorityAPI({ id });
  } else {
    await closeAuthorityAPI({ id });
  }
  PxMessage.success("操作成功");
};

// 获取父级权限，看看切换按钮是否可以切换
const getSwitchDisabledStatus = async () => {
  try {
    const res = await getAuthorityAPI({ id: props.currentNode?.id, type: "role" });
    if (res?.authFlag) {
      state.switchDisabled = res?.authFlag === "Y" ? true : false;
    }
  } catch (error) {
    console.log(error);
  }
};
const init = async () => {
  try {
    state.loading = true;
    const res = await getAuthorityAPI({ id: props.rowData.id, type: "role" });
    state.authorityFlag = res?.authFlag === "Y";
    state.tableData = res === null ? [] : res?.data;
    state.tableData?.forEach(item => {
      item.name = item.roleName;
      item.preview = formatYN(item.preview);
      item.download = formatYN(item.download);
      item.edit = formatYN(item.edit);
      item.manage = formatYN(item.manage);
      item.readOnly = formatYN(item.readOnly);
    });
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
    state.tableSelectedData = [];
  }
};

// 表格勾选
const tableSelect = val => {
  state.tableSelectedData = val;
};

const selecTable = row => {
  return row?.readOnly ? false : true;
};

// 编辑
const handleEdit = (row, index) => {
  state.tableData[index].isEdit = true;
};

// 当勾选下载/编辑/删除/管理时，预览自动被勾选
const changeLimit = (val, row) => {
  if (val) {
    row.preview = true;
  }
};

// 删除
const handleDelete = async (row, index) => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      if (row.id) {
        await deleteAuthorityAPI({ rowId: [row.rowId] });
      } else {
        state.tableData.splice(index, 1);
      }
      PxMessage.success("删除成功");
      init();
    })
    .catch(() => {});
};

// 保存
const handleSave = async (row, index) => {
  const params = {
    id: props.rowData.id,
    rowId: row?.rowId,
    roleKey: row.roleKey,
    roleName: row.name,
    preview: row.preview ? "Y" : "N",
    download: row.download ? "Y" : "N",
    edit: row.edit ? "Y" : "N",
    manage: row.manage ? "Y" : "N"
  };
  await saveAuthorityAPI(params);
  state.tableData[index].isEdit = false;
  PxMessage.success("保存成功");
};

// 取消
const handleCancel = (row, index) => {
  state.tableData[index].isEdit = false;
};

const getSelectList = async type => {
  try {
    state.selectLoading = true;
    if (type === "person") {
      // 人员
      state.optionList = await getPersonListAPI();
      state.optionList.forEach(item => {
        item.id = item.userId;
        item.label = `${item.username}-${item.realName}`;
        item.value = item.userId;
      });
    } else if (type === "role") {
      // 角色
      state.optionList = await getRoleListAPI();
      state.optionList.forEach(item => {
        item.id = item.roleId;
        item.label = item.roleName;
        item.value = item.roleId;
      });
    } else if (type === "work") {
      // 岗位
      state.optionList = await getWorkListAPI();
      state.optionList.forEach(item => {
        item.id = item.positionId;
        item.label = item.positionName;
        item.value = item.positionId;
      });
    } else if (type === "organization") {
      // 组织
      state.optionList = await getOrganizationListAPI();
      renameLabel(state.optionList);
    }
  } catch (err) {
    console.log(err);
  } finally {
    state.selectLoading = false;
  }
};

const renameLabel = data => {
  data.forEach(item => {
    item.label = item.deptName;
    item.value = item.deptId;
    if (item.children) {
      renameLabel(item.children);
    }
  });
};

// 添加
const addPerson = () => {
  state.optionList = [];
  state.selectedOption = [];
  getSelectList(activeName.value);
  state.addDialogVisible = true;
};

const cancelAdd = () => {
  state.addDialogVisible = false;
};

// Y N 转成true false
const formatYN = data => {
  return data === "Y" ? true : false;
};

// 树形数据扁平化
const treeToArray = treeData => {
  let res = [];
  treeData.forEach(el => {
    res.push(el);
    el.children && res.push(...treeToArray(el.children));
  });
  return res;
};

const confirmAdd = () => {
  state.selectedOption.map(item => {
    if (state.tableData.filter(v => v.name === item.label).length === 0) {
      state.tableData.push({
        id: props.rowData.id,
        selectedId: activeName.value === "organization" ? treeToArray(state.optionList).find(v => v.deptId === item).deptId : item.id,
        name: activeName.value === "organization" ? treeToArray(state.optionList).find(v => v.deptId === item).deptName : item.label,
        roleKey: activeName.value === "role" ? item.roleKey : null,
        preview: false,
        download: false,
        edit: false,
        delete: false,
        manage: false,
        isEdit: false,
        readOnly: false
      });
    }
  });
  state.addDialogVisible = false;
};

// 批量删除
const deletePerson = () => {
  if (state.tableSelectedData?.length) {
    PxMessageBox.confirm("是否确认删除？", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(async () => {
        const data = state.tableSelectedData;
        const savedData = data.map(item => item.rowId);
        await deleteAuthorityAPI({ rowId: savedData?.length > 0 ? savedData : [null] });
        PxMessage.success("删除成功");
        init();
      })
      .catch(() => {});
  } else {
    PxMessage.warning("请选勾选要删除的角色");
  }
};
</script>

<style lang="scss">
.authority-container {
  box-sizing: border-box;
  width: 100%;
  height: calc(100vh - 133px);
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;

  .top-nav {
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;

    .nav-location {
      display: flex;
      align-items: center;
      margin: 0 18px;

      .current-folder {
        font-size: 14px;
        color: rgb(0 0 0 / 20%);
      }
    }

    .flag-status {
      margin-left: 8px;
    }

    .active-status {
      color: #3b82f6;
    }
  }

  .handle-btn {
    margin: 8px 0;
  }
}
</style>
